import { Component, Vue } from 'vue-property-decorator';
import InfoBlock from '@profile/util/info_block/Index.vue';
import user_axios from '@axios/user';
import project_axios from '@axios/project';
import { User } from '@/assets/js/entity/user';

@Component({
    components: {
        InfoBlock
    }
})
export class Goodness extends Vue {

    /** 我的强项 */
    private myGoodness: Array<string> = String.prototype.deepCopy(this.$store.getters.me().goodness);

    /** 数据库中存在的所有强项列表 */
    private dbTags: Array<string> = [];

    /** 可供选择的强项列表 */
    private finalSelection: Array<string> = [];

    /** 搜索关键字 */
    private searchKeywords: string = '';

    /** 源数据 */
    private source: string = JSON.stringify(this.$store.getters.me(true));

    /**
     * 从服务端拉取强项列表, 剔除我已经选择的部分
     * 并存为源数据
     */
    created() {
        project_axios.base.getTags().then((res: Array<string>) => {
            this.myGoodness.forEach(item => {
                let index: number = res.indexOf(item);
                if (index != -1) {
                    res.splice(index, 1);
                }
            })
            this.dbTags = res;
            this.finalSelection = res;
        })
    }

    /** 
     * 从我的强项中删除一项, 添加回可供选择列表
     */
    private doDelete(item: string, index: number): void {
        this.dbTags.push(item)
        this.myGoodness.splice(index, 1);
        this.keywordChange();
    }

    /** 
     * 从可供选择列表删除一项, 添加为我的强项
     */
    private doSelect(item: string, index: number): void {
        if (this.myGoodness.length == 3) {
            '最多只能选择 3 个强项'.notifyWarn();
            return;
        }
        this.myGoodness.push(item)
        this.dbTags.splice(index, 1);
        this.keywordChange();
    }

    /** 
     * 当输入的关键字发生变化时自动调用
     */
    private keywordChange(): void {
        this.finalSelection = [];
        this.dbTags.forEach(item => {
            if (item.contain(this.searchKeywords)) {
                this.finalSelection.push(item)
            }
        })
    }

    /**
     * 更新信息, 服务端更新成功后才更新本地
     */
    private save(): void {
        user_axios.update.goodness(this.$store.getters.me().id, this.myGoodness).then(res => {
            if (res) {
                let me: User = this.$store.getters.me();
                me.goodness = this.myGoodness;
                this.source = this.$store.getters.updateMe(me);
            }
        });
    }

    /**
     * 判断是否进行了修改
     * 只需要将当前数据与源数据进行比较即可
     */
    private changed(): boolean {
        return  this.source.isEmpty() || JSON.stringify(this.myGoodness) === this.source;
    }
}